<template>
  <div class="root">
    <div>
      <!-- <img alt="Vue logo" src="../assets/logo.png" /> -->
    </div>
    <div class="home">
      <div class="left">
        <div style="display: flex;margin:10px 0; ">
          <el-input placeholder="搜索姓名" v-model="filterText"></el-input>
          <el-button type="primary" class="add-btn" @click="addTopUser">添加顶级用户</el-button>
        </div>
        <el-tree
          ref="tree"
          :data="data"
          :props="defaultProps"
          @node-click="handleNodeClick"
          :expand-on-click-node="false"
          :highlight-current="true"
          :accordion="true"
          :filter-node-method="filterNode"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button type="text" size="mini" @click="() => append(data)">添加下级</el-button>
            </span>
          </span>
        </el-tree>
        <el-dialog title="添加下级" :visible="dialogVisible" width="500px" :show-close="false">
          <el-form
            :model="form"
            label-width="80px"
            label-position="right"
            :rules="rules"
            ref="ruleForm"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="金额" prop="price">
              <el-input v-model.number="form.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="加入时间" prop="date">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择加入时间"
                value-format="timestamp"
              ></el-date-picker>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <div class="right">
        <div v-if="currentAppendData">
          <p class="title">{{currentAppendData.name}}</p>
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">入会金额：{{currentAppendData.price}}</div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple-light">入会时间：{{currentAppendData.date|formatDate}}</div>
            </el-col>
          </el-row>
          <div>
            <p class="list-title">直属下级列表</p>
            <el-table
              :data="currentAppendData.children"
              style="width: 100%"
              v-if="currentAppendData.children&&currentAppendData.children.length"
            >
              <el-table-column prop="name" label="姓名"></el-table-column>
              <el-table-column prop="price" label="入会金额"></el-table-column>
              <el-table-column prop="date" label="日期">
                <template slot-scope="scope">{{scope.row.date|formatDate}}</template>
              </el-table-column>
            </el-table>
            <div v-else style="color:red">无下级</div>
          </div>
        </div>
        <div v-else>请选择左侧节点姓名</div>
      </div>
    </div>
  </div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
// import moniData from "@/data/index.js";
import moment from "moment";
export default {
  name: "home",
  components: {
    HelloWorld
  },
  filters: {
    formatDate(value) {
      return moment(value).format("YYYY-MM-DD");
    }
  },
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name"
      },
      dialogVisible: false,
      form: {
        name: "",
        price: 20000,
        date: ""
      },
      currentAppendData: null,
      data: null,
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        price: [
          { required: true, message: "金额不能为空", trigger: "change" },
          { type: "number", message: "请输入正确的金额" }
        ],
        date: [
          {
            required: true,
            message: "请选择加入时间"
          }
        ]
      },
      filterText: "",
      isTopUser: false
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.userData = [];
    this.$store.state.userData.forEach(item=>{
      this.userData.push(Object.assign({},item));
    })
  },
  mounted() {
    this.data = this.formatTreeData();
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    formatTreeData() {
      const formatData = [];
      let that = this;
      const getChildren = function(pid, arr) {
        that.userData.forEach(item => {
          if (item.parentId === pid) {
            if (pid) {
              if (!arr.children) {
                arr.children = [];
              }
              arr.children.push(item);
            } else {
              arr.push(item);
            }
            getChildren(item.id, item);
          }
        });
      };
      getChildren("", formatData);
      return formatData;
    },
    handleNodeClick(data) {
      this.currentAppendData = data;
    },
    append(data) {
      this.isTopUser = false;
      this.dialogVisible = true;
      this.currentAppendData = data;
    },
    addUser() {
      const newChild = {
        parentId: this.isTopUser ? "" : this.currentAppendData.id,
        parentName: this.isTopUser ? "" : this.currentAppendData.name,
        id: Math.floor(Math.random() * 100000000),
        name: this.form.name,
        price: this.form.price,
        date: this.form.date,
        // children: []
      };
      if (this.isTopUser) {
        this.data.push(newChild);
      } else {
        if (!this.currentAppendData.children) {
          this.$set(this.currentAppendData, "children", []);
        }
        this.currentAppendData.children.push(newChild);
      }
      this.$store.commit('addUser',Object.assign({},newChild));
      this.dialogVisible = false;
    },
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$message({
            message: "添加用户成功",
            type: "success"
          });
          this.addUser();
        } else {
          return false;
        }
      });
    },
    checkPrice(rule, value, callback) {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          return callback(new Error("请输入正确的金额"));
        }
      });
    },
    // 添加顶级用户
    addTopUser() {
      this.isTopUser = true;
      this.dialogVisible = true;
    }
  }
};
</script>
<style lang="less" scoped>
.root {
  height: calc(100% - 100px);
}

.custom-tree-node {
  display: flex;
  /* justify-content: space-between; */
  align-items: center;
}

.custom-tree-node > span:last-child {
  margin-left: 20px;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100% !important;
}

.home {
  display: flex;
  margin-top: 20px;
  height: 100%;

  .left {
    width: 30%;
  }

  .right {
    padding: 20px;
    background: #f8f8f8;
    flex-grow: 1;

    .title {
      border-bottom: 2px solid #000;
      margin-bottom: 10px;
      line-height: 2;
      font-size: 20px;
      font-weight: bold;
    }
  }
}
.add-btn {
  width: 160px;
  margin: 0 10px !important;
  padding: 0 10px !important;
}
.list-title {
  font-size: 16px;
  line-height: 2;
  margin-top: 10px;
}
/deep/ .el-tree-node .el-button {
  padding:0 !important;
}
</style>